package org.lee.ico;

import net.sf.image4j.codec.ico.ICODecoder;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

/**
 * DownloadIcoDemo
 * 下载ico
 *
 * @author dralee
 * @date 2021-12-30 11:05:32
 **/
public class DownloadIcoDemo extends JFrame {
    public DownloadIcoDemo() throws HeadlessException {
        initUI();
    }

    private void initUI() {
        List<BufferedImage> images = readImage();
        ImageIcon icon = new ImageIcon(images.get(0));
        JLabel lbl = new JLabel(icon);

        createLayout(lbl);

        setTitle("Ico image");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private void createLayout(JLabel lbl) {
        Container pane = getContentPane();
        GroupLayout gl = new GroupLayout(pane);
        pane.setLayout(gl);

        gl.setAutoCreateGaps(true);
        gl.setAutoCreateContainerGaps(true);
        gl.setHorizontalGroup(gl.createSequentialGroup().addComponent(lbl));
        gl.setVerticalGroup(gl.createParallelGroup().addComponent(lbl));

        pack();
    }

    private List<BufferedImage> readImage() {
        List<BufferedImage> images = null;
        String url = "https://www.baidu.com/favicon.ico";
        try (InputStream is = new URL(url).openStream()) {
            images = ICODecoder.read(is);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return images;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> new DownloadIcoDemo().setVisible(true));
    }
}
